package com.jzoffer2;


import ds.TreeNode;

import java.util.*;

/**
 * TODO
 *
 * @author lefly
 * @version 1.0
 * @classname No32_1
 * @description
 * @date 2021/1/30 下午5:10
 */
public class No32_1 {
    public static void main(String[] args) {
        TreeNode t1 = new TreeNode(3);
        TreeNode t2 = new TreeNode(9);
        TreeNode t3 = new TreeNode(20);
        TreeNode t4 = new TreeNode(15);
        TreeNode t5 = new TreeNode(7);
        t1.left = t2;
        t1.right = t3;
        t3.left = t4;
        t3.right = t5;
        int[] res = levelOrder(t1);
        System.out.println(Arrays.toString(res));
    }

    public static int[] levelOrder(TreeNode root) {
        List<Integer> temp = new ArrayList<>();
        if(root == null){
            return new int[0];
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode t = queue.poll();
                temp.add(t.val);
                if(t.left != null){
                    queue.offer(t.left);
                }
                if(t.right != null){
                    queue.offer(t.right);
                }
            }
        }
        int[] res = new int[temp.size()];
        for (int i = 0; i < temp.size(); i++) {
            res[i] = temp.get(i);
        }
        return res;
    }

}
